package com.cxb.demotest.service.impl;

import com.cxb.demotest.dao.mapper_one.UserOneMapper;
import com.cxb.demotest.dao.mapper_two.UserTwoMapper;
import com.cxb.demotest.exception.HelloRetryException;
import com.cxb.demotest.service.UserService;
import java.time.LocalDateTime;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * @author Xbao
 * @version 1.0
 * @description
 * @date 2021/5/7 14:10
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

  private int times = 0;

  @Autowired
  private UserOneMapper userOneMapper;

  @Autowired
  private UserTwoMapper userTwoMapper;

  @Override
  public String queryAllNames() {
    List<String> strings = userOneMapper.queryAutoBotsNames();
    List<String> strings1 = userTwoMapper.queryDeceptronsNames();
    return "Autobots:"+ strings + "Deceptrons:"+strings1;
  }

  @Override
  @Retryable(value = HelloRetryException.class, maxAttempts = 5)
  public String helloWithSpringRetry() {
    times = incrementAndGet(times);
    log.info("hello times : {}", times);

    if(times % 4 != 0){
      log.warn("发生异常,time : {}", LocalDateTime.now());
      throw new HelloRetryException("发送hello异常", "200001");
    }

    times = 0;
    return "hello";
  }

  @Override
  public String helloWithGuavaRetry() {
    times = incrementAndGet(times);
    log.info("hello times : {}", times);

    if(times % 4 != 0){
      log.warn("发生异常,time : {}", LocalDateTime.now());
      throw new HelloRetryException("发送hello异常", "200001");
    }

    times = 0;
    return "hello";
  }

  private Integer incrementAndGet(int times){
    times = times + 1;
    return times;
  }


}
